import utime
import modbus as mb
import m31


'''
M31-AAAX4440G采用标准 Modbus- RTU 协议的继电器设备
配置:4DI+4AI+4DO
将地址调为2,拨动拨码重启后生效
'''
m3Obj = m31.M31(mb,2)
#初始化
def mb_init():
    ret = mb.init('modbus_485_9600')
    if ret < 0:
        raise ValueError("init modbus failed.")

#控制单路DO开关
def control_coil():
    m3Obj.openChannel(0)
    utime.sleep(1)
    m3Obj.openChannel(1)
    utime.sleep(1)
    m3Obj.openChannel(2)
    utime.sleep(1)
    m3Obj.openChannel(3)
    utime.sleep(1)
    status = m3Obj.getreadCoils()
    print("DO:", status[0])
    utime.sleep(5)
    m3Obj.closeChannel(0)
    utime.sleep(1)
    m3Obj.closeChannel(1)
    utime.sleep(1)
    m3Obj.closeChannel(2)
    utime.sleep(1)
    m3Obj.closeChannel(3)
    utime.sleep(1)
    status = m3Obj.getreadCoils()
    print("D0:", status[0])

#同时控制4路DO开
def open_all_DO():
    m3Obj.writeMultipleCoilsChannel(0xff)

#同时控制4路DO关
def close_all_DO():
    m3Obj.writeMultipleCoilsChannel(0)


#同时读取4路DI:di1:1;di2:2;di3:4;di4:8
def read_DI():
    di = m3Obj.getreadDiscreteInputs()
    print("DI:", di[0])

#同时读取4路AI工程量整形值寄存器数值
def read_AI():
    ai = m3Obj.getreadInputRegisters()
    print('AI:',ai)

#AI 采样范围寄存器，寄存器地址（0x0DAC）写入范围后读取，0 表示 0-20mA， 1 表示 4-20mA
def write_Registers():
    m3Obj.wwriteMultipleHoldingRegisters()  #4路同时写入1
    m3Obj.getreadHoldingRegisters()     #读取
    m3Obj.wwriteHoldingRegister()       #第一路改成0
    m3Obj.getreadHoldingRegisters()     #读取


if __name__ == '__main__':
    mb_init()
    control_coil()
    open_all_DO()
    utime.sleep(1)
    close_all_DO()
    read_DI()
    read_AI()
    write_Registers()
    while True:
        utime.sleep(1)


